<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Exception\Handler;

use App\Constants\HttpCode;
use App\Traits\ApiResponseTrait;
use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\Database\Exception\QueryException;
use Hyperf\ExceptionHandler\ExceptionHandler;
use Hyperf\HttpMessage\Exception\HttpException;
use Hyperf\HttpMessage\Exception\MethodNotAllowedHttpException;
use Hyperf\HttpMessage\Stream\SwooleStream;
use Hyperf\Validation\ValidationException;
use MongoDB\Driver\Exception\ConnectionException;
use Psr\Http\Message\ResponseInterface;
use Throwable;

class AppExceptionHandler extends ExceptionHandler
{
    use ApiResponseTrait;

    /**
     * @var StdoutLoggerInterface
     */
    protected $logger;

    public function __construct(StdoutLoggerInterface $logger)
    {
        $this->logger = $logger;
    }

    public function handle(Throwable $throwable, ResponseInterface $response)
    {
        //判断请求方式
        if ($throwable instanceof MethodNotAllowedHttpException) {
            $this->stopPropagation();
            return $this->fail('请求方法应为' . $throwable->getMessage());
        }
        //sql查询异常监听
        if ($throwable instanceof QueryException) {
            $this->stopPropagation();
            return $this->fail('数据查询错误'.$throwable->getMessage());
        }
        if ($throwable instanceof HttpException) {
            $this->stopPropagation();
            return $this->setHttpCode(HttpCode::SERVER_ERROR)->fail('访问地址不存在');
        }
        if ($throwable instanceof ValidationException) {
            $this->stopPropagation();
            return $this->setHttpCode(HttpCode::SERVER_ERROR)->fail($throwable->validator->errors()->first());
        }

        $this->logger->error(sprintf('%s[%s] in %s', $throwable->getMessage(), $throwable->getLine(), $throwable->getFile()));
        $this->logger->error($throwable->getTraceAsString());
        return $this->fail($throwable->getMessage());
    }

    public function isValid(Throwable $throwable): bool
    {
        return true;
    }
}
